package com.example.musicplayer

import android.Manifest
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.database.Cursor
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity(), ServiceConnection {

    val tag = "MainActivity"
    var binder: MusicService.MusicBinder? = null
    lateinit var seekBar: SeekBar
    private val REQUEST_CODE_POST_NOTIFICATIONS = 1

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        seekBar = findViewById(R.id.seekBar)
        startMusicService()
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser){
                    binder?.currentPosition = progress
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

    }

    private fun startMusicService() {
        val serviceIntent = Intent(this, MusicService::class.java)
        serviceIntent.putExtra(MusicService.Command, 1)
        startService(serviceIntent)
        bindService(serviceIntent, this, BIND_AUTO_CREATE)
    }

    fun onPlay(v: View) {
        val serviceIntent = Intent(this, MusicService::class.java)
        serviceIntent.putExtra(MusicService.Command, 1)
        startService(serviceIntent)
    }

    fun onPause(v: View) {
        val serviceIntent = Intent(this, MusicService::class.java)
        serviceIntent.putExtra(MusicService.Command, 2)
        startService(serviceIntent)
    }

    fun onStop(v: View) {
        val serviceIntent = Intent(this, MusicService::class.java)
        serviceIntent.putExtra(MusicService.Command, 3)
        startService(serviceIntent)
    }

    fun onNext(v: View) {
        val serviceIntent = Intent(this, MusicService::class.java)
        serviceIntent.putExtra(MusicService.Command, 4)
        startService(serviceIntent)
    }

    fun onPrev(v: View) {
        val serviceIntent = Intent(this, MusicService::class.java)
        serviceIntent.putExtra(MusicService.Command, 5)
        startService(serviceIntent)
    }

    private fun requestPermissionsIfNeeded() {
        val permissionsToRequest = mutableListOf<String>()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.POST_NOTIFICATIONS)
            }
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.READ_MEDIA_AUDIO)
        }

        if (permissionsToRequest.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, permissionsToRequest.toTypedArray(), 0)
        } else {
            startMusicService()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }


    override fun onDestroy() {
        super.onDestroy()
        unbindService(this)
    }

    @SuppressLint("SetTextI18n")
    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        binder = service as MusicService.MusicBinder

        thread {
            while (binder != null) {
                Thread.sleep(1000)
                runOnUiThread {
                    seekBar.max = binder!!.duration
                    seekBar.progress = binder!!.currentPosition
                    val mn = findViewById<TextView>(R.id.textView_name)
                    mn.text = binder!!.musicName
                    val count = findViewById<TextView>(R.id.textView_count)
                    count.text = "${binder!!.currentIndex + 1}/${binder!!.size}"

                    val img = findViewById<ImageView>(R.id.imageView)
                    img.setImageResource(binder!!.musicImage)

                    //NotificationUtil.sendNotification(this@MainActivity, binder!!.musicName)
                }
            }
        }
    }

    override fun onServiceDisconnected(name: ComponentName?) {
        binder = null
    }
}